import '../../../public.dart';

class CommonPinInput extends StatefulWidget {
  final List<TextEditingController> controllers;
  final List<FocusNode> focusNodes;
  final int pinLength;
  final ValueChanged<String>? onPinChanged;
  final ValueChanged<String>? onPinCompleted;
  final Widget? title;
  final Widget? subtitle;
  final Color? focusColor;
  final Color? borderColor;
  final double? boxSize;
  final double? borderWidth;
  final double? borderRadius;

  const CommonPinInput({
    super.key,
    required this.controllers,
    required this.focusNodes,
    this.pinLength = 4,
    this.onPinChanged,
    this.onPinCompleted,
    this.title,
    this.subtitle,
    this.focusColor = const Color(0xFF1DE9B6),
    this.borderColor = const Color(0xFFE0E0E0),
    this.boxSize = 60,
    this.borderWidth = 2,
    this.borderRadius = 12,
  });

  @override
  State<CommonPinInput> createState() => _CommonPinInputState();
}

class _CommonPinInputState extends State<CommonPinInput> {
  String _currentPin = '';
  late List<VoidCallback> _listeners;

  @override
  void initState() {
    super.initState();
    // 创建监听器列表
    _listeners = List.generate(
      widget.controllers.length,
      (i) =>
          () => _onControllerChanged(i),
    );
    // 为每个控制器添加监听器
    for (int i = 0; i < widget.controllers.length; i++) {
      widget.controllers[i].addListener(_listeners[i]);
    }
  }

  @override
  void dispose() {
    // 移除监听器
    for (int i = 0; i < widget.controllers.length; i++) {
      widget.controllers[i].removeListener(_listeners[i]);
    }
    super.dispose();
  }

  void _onControllerChanged(int index) {
    final pin = widget.controllers
        .map((controller) => controller.text)
        .join('');
    if (pin != _currentPin) {
      setState(() {
        _currentPin = pin;
      });
      widget.onPinChanged?.call(pin);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (widget.title != null) widget.title!,
        if (widget.subtitle != null) ...[
          const SizedBox(height: 12),
          widget.subtitle!,
        ],
        const SizedBox(height: 60),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: List.generate(
            widget.pinLength,
            (index) => _buildPinInputBox(index),
          ),
        ),
      ],
    );
  }

  Widget _buildPinInputBox(int index) {
    final isFilled = widget.controllers[index].text.isNotEmpty;
    final focusColor = isFilled
        ? (widget.focusColor ?? const Color(0xFF1DE9B6))
        : (widget.borderColor ?? const Color(0xFFE0E0E0));

    return Container(
      width: widget.boxSize ?? 60,
      height: widget.boxSize ?? 60,
      decoration: BoxDecoration(
        border: Border.all(color: focusColor, width: widget.borderWidth ?? 2),
        borderRadius: BorderRadius.circular(widget.borderRadius ?? 12),
      ),
      child: TextField(
        controller: widget.controllers[index],
        focusNode: widget.focusNodes[index],
        keyboardType: TextInputType.number,
        obscureText: true,
        maxLength: 1,
        textAlign: TextAlign.center,
        style: const TextStyle(
          fontSize: 24,
          fontWeight: FontWeight.w600,
          color: Colors.black87,
        ),
        decoration: const InputDecoration(
          border: InputBorder.none,
          counterText: '',
        ),
        onChanged: (value) {
          _handleInputChange(index, value);
        },
        onSubmitted: (value) {
          if (index == widget.pinLength - 1) {
            // 当最后一个输入框完成时，重新构建当前PIN并触发回调
            final currentPin = widget.controllers
                .map((controller) => controller.text)
                .join('');
            if (currentPin.length == widget.pinLength) {
              widget.onPinCompleted?.call(currentPin);
            }
          }
        },
      ),
    );
  }

  void _handleInputChange(int index, String value) {
    if (value.isNotEmpty && index < widget.pinLength - 1) {
      // 自动跳转到下一个输入框
      widget.focusNodes[index + 1].requestFocus();
    } else if (value.isEmpty && index > 0) {
      // 删除时跳转到上一个输入框
      widget.focusNodes[index - 1].requestFocus();
    }
  }
}
